package com.zhj.bz.datastructure.queue;

/**
 * @author zhj
 */
public class RingArrayQueue {

    /*
    最大容量
     */
    private int maxSize;

    /*
    队列头
     */
    private int front;

    /*
    队列尾的后一个元素
     */
    private int rear;

    /*
    队列
     */
    private int[] arr;

    public RingArrayQueue(int maxSize) {
        this.maxSize = maxSize + 1;
        arr = new int[this.maxSize];
        front = 0;
        rear = 0;
    }

    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    public boolean isEmpty() {
        return rear == front;
    }

    /**
     * 添加数据
     * @param n
     */
    public void addData(int n) {
        if (isFull()) {
            System.out.println("队列已满！");
            return;
        }
        arr[rear] = n;
        rear = (rear + 1) % maxSize;
    }

    public int getData() {
        if (isEmpty()) {
            throw new RuntimeException("队列空，无数据可取！");
        }
        int res = arr[front];
        front = (front + 1) % maxSize ;
        return res;
    }

    public void show() {
        if (isEmpty()) {
            System.out.println("队列为空");
            return;
        }
        System.out.println("队列数据为：");
        for (int i = front; i < front + size(); i++) {
            System.out.print(arr[i % maxSize] + "\t");
        }
        System.out.println();
    }

    public int size() {
        return (rear + maxSize - front) % maxSize;
    }

    public int headQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空，没有数据");
        }
        return arr[front];
    }
}
